(function($){
	String.prototype.format = function() {
		var args = arguments;
		return this.replace(/{(\d+)}/g, function(match, number) { 
			return typeof args[number] != 'undefined'
				? args[number]
				: match;
		});
	};

	$.cameraRoll = {
		// Open dialog that is sent to function
		openDialog : function(dialog){
			if(!$('.ui-widget-overlay').length > 0){
				dialog.dialog("open");
			}
		},
		
		// Hide all dialog close x's on the page that calls the function
		hideDialogClose : function(){
			$('.ui-dialog-titlebar-close').hide();
		},

		// Close the menu when clicked
		menuClose : function() {
			$('.content').hide();
		},
		
		// Build the default dialog with set title and given dialog div
		buildDialog : function(options){
			var settings = $.extend({
				autoOpen: false,
				modal: true,
				resizable: false,
				draggable: false,
				position: ['middle', 80],
				title: ''
			}, options);

			$(settings.selector).dialog( {
				autoOpen: settings.autoOpen,
				modal: settings.modal,
				title: settings.title,
				resizable: settings.resizable,
				draggable: settings.draggable,
				position: settings.position
			});
		},

		//Build the cancel resets when cancel button is clicked in dialog
		resetDialog : function(options){
			var settings = $.extend({
				inputs: []
			}, options);
			
			$(settings.dialog).dialog("close");
			
			$.each(settings.inputs, function(key, element){
				if($('#upload-file').attr('type') == 'text') {
					element.val('');
					element.removeClass('errorField');
				}
				else if($('#upload-file').attr('type') == 'file') {
					element.val("");
					element.removeClass('errorField');
				}
			});
		}, 

		//Sign in to site
		login : function(options) {
			var settings = $.extend ({
				errorField: $('.error')
			}, options);

			var userName = $(settings.userName).val();
			var password = $(settings.password).val();

			$.getJSON("./cameraRollPhp/login.php?userName=" + userName + "&password=" + password, function (data) {
				if(data.success){
					window.location.href = "./cameraRollHome.php";
					window.location.reload();
				}
				else{
					$(settings.errorField).show();
				}
			});
		},

		signUp : function(options) {
			var settings = $.extend({
				userSettings: {},
				emailBox: null,
				confirmEmailBox: null
			}, options);

			if($.cameraRoll.validateEmail(settings.userSettings.email)){
				if(settings.userSettings.email != settings.userSettings.confirmEmail){
					$(settings.confirmEmailBox).addClass('errorField');
				}
				else{
					$.getJSON("cameraRollPhp/signUp.php?userName=" + settings.userSettings.userName + "&password=" + settings.userSettings.password + "&email=" + settings.userSettings.email, function(data){
						console.log(data);
						if(data.success){
							window.location.href = "./cameraRollHome.php";
							window.location.reload();
						}
						if(!data.newUser){
							$(settings.userError).show();
						}
					});
				}
			}
			else{
				$(settings.emailBox).addClass('errorField');
			}
		},

		validateEmail : function (email) {
			var re = /\S+@\S+\.\S+/
			return re.test(email);
		},

		//Hide all error fields on a page
		hideErrorFields : function(){
			$('.error').hide();
		},

		//View specific album link clicked
		viewPhotos : function(album) {
			$.getJSON("cameraRollPhp/viewPhotos.php?album=" + album , function(data){
				if(data.success){
					var carousel = $('#CameraRollCarousel div center');
					carousel.html('');
					$('#albumTitle').html((data.albumTitle != "default" ? data.albumTitle + " Album" : "Camera Roll"));
					$('#albumTitle').data('album', data.albumTitle != "default" ? data.albumTitle + " Album" : "default");
					$.each(data.images, function(key, image){
						if(key == 0){
							carousel.append('<div class="active item"><img src="' + image + '"></div>')
						}
						else{
							carousel.append('<div class="item"><img src="' + image + '"></div>')
						}
					});

					var carouselParent = $('#CameraRollCarousel').parent();
					$('#CameraRollCarousel').carousel({
						interval: 4000
					});

					$('img').click(function () {
						$.cameraRoll.viewImage(this);
					});
				}
			});
		},

		//Build a dropdown box for the upload popup
		buildDropdown : function(data, userName) {

			var dropdownBox = '';
				
			$.each(data.albums, function(key, album){
				var albumLink;
				if(album != "default"){
					dropdownBox += '<option data-album="' + album + '">' + album + '</option>';
				}else{
					dropdownBox += '<option data-album="default">' + userName + '\'s Camera Roll</option>';
				}
			});

			$('#dropdownBox').html(dropdownBox);
		},

		buildRemoveAlbumDropdown : function(data, userName){
			var dropdownBox = '';
			$.each(data.albums, function(key, album){
				var albumLink;
				if(album != "default"){
					dropdownBox += '<option data-album="' + album + '">' + album + '</option>';
				}
			});

			$('#deleteDropdownBox').html(dropdownBox);
		},
		
		// create album
		createAlbum : function(options) {
			var settings = $.extend({
				errorField: null
			}, options);

			$.getJSON('cameraRollPhp/addAlbum.php?albumName=' + settings.albumName.val(), function (data) {
				if (data.success) {
					$('#addAlbum-cancel').click();
					$.getJSON("cameraRollPhp/viewAlbums.php", function (data) {
						$.cameraRoll.buildMenu(document.width, data, settings.userName);
						$.cameraRoll.buildDropdown(data, userName);
					});
				}
			});
		},

		//Build the menu sidebar with the albums pulled from the server
		buildMenu : function(width, data, userName){
			if( width > 767 ){
				var popOutMenu = ''
					+ '<ul id="menu" class="menuProps">'
					+ '<li>'
						+ '<a href="#">Photos</a>'
						+ '<ul id="photos">'
							+ '<li id="upload">'
								//link this to the dropdownBox popup
								+ '<a href="#">Upload</a>'
							+ '</li>'
							+ '<li>'
								+ '<a href="./viewAll.php">View All</a>'
							+ '</li>'
						+ '</ul>'
					+ '</li>'
					+ '<li>'
						+ '<a href="#">Albums</a>'
						+ '<ul id="albums">'
							+ '<li id="createAlbum">'
								+ '<a href="#">Create</a>'
							+ '<li>'
								+ '<a href="#">View Albums</a>'
								+ '<ul id="albumsList">';

								$.each(data.albums, function(key, album){
									var albumLink;
									if(album != "default"){
										popOutMenu += '<li><a href="./cameraRollHome.php?album=' + album + '" class="album-link" data-album="' + album + '" >' + album + '</a></li>';
									}else{
										popOutMenu += '<li><a href="./cameraRollHome.php" class="album-link" data-album="default">' + userName + '\'s Camera Roll</a></li>';
									}
								});
								
							popOutMenu += ''
							 	+ '</ul>'
							+ '</li>'
							+ '<li id=remove>'
								+ '<a href="#">Remove</a>'
							+ '</li>'
						+ '</ul>'
					+ '</li>'
				+ '</ul>';

				$('#sideBar').html(popOutMenu);
				$('#menu').menu();
			}
			else{
				var accordionMenu = ''
					+ '<div class="accordion" id="menu">'
						+ '<div class="accordion-group">'
							+ '<div class="accordion-heading">'
								+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#menu" href="#collapseOne" id="menuOpenClose"><h4>Menu Options</h4></a>'
							+ '</div>'
							+ '<div id="collapseOne" class="accordion-body collapse">'
								+ '<h4>Photos</h4>'
								+ '<ul id="photos">'
									+ '<li id="upload">'
										+ '<a href="#">Upload</a>'
									+ '</li>'
									+ '<li id="viewAll">'
										+ '<a href="./viewAll.php">View All</a>'
									+ '</li>'
								+ '</ul>'
								+ '<h4>Albums</h4>'
								+ '<ul id="albums">'
									+ '<li id="createAlbum">'
										+ '<a href="#">Create</a>'
									+ '<li>'
										+ 'View Albums'
										+ '<ul id="albumsList">';

										$.each(data.albums, function(key, album){
											var albumLink;
											if(album != "default"){
												accordionMenu += '<li><a href="./cameraRollHome.php?album=' + album + '" class="album-link" data-album="' + album + '" >' + album + '</a></li>';
											}else{
												accordionMenu += '<li><a href="./cameraRollHome.php" class="album-link" data-album="default">' + userName + '\'s Camera Roll</a></li>';
											}
										});

									accordionMenu += ''
										+ '</ul>'
									+ '</li>'
								+ '</ul>'
							+ '</div>'
						+ '</div>'
					+ '</div>';

				$('#sideBar').html(accordionMenu);
			}

			$('.album-link').click(function(event){
				$('#menuOpenClose').click();
			});

			// Manage profile click to open dialog
			$('[name="navManageProfile"]').click(function(){
				$.cameraRoll.openDialog($('#navManageProfile'));
				$.cameraRoll.manageProfile({
					firstName: $('#firstName'),
					lastName: $('#lastName')
				});
				$('#accountOptions').css('visibility', 'hidden');
				return false;	
			});
			
			// Change password click to open dialog
			$('[name="navChangePassword"]').click(function(){
				$.cameraRoll.openDialog($('#navChangePassword'));
				$('#accountOptions').css('visibility', 'hidden');
				return false;
			});

			// Change email click to open dialog
			$('[name="navChangeEmail"]').click(function(){
				$.cameraRoll.openDialog($('#navChangeEmail'));
				$('#accountOptions').css('visibility', 'hidden');
				return false;
			});
			
			// Upload click to open dialog
			$('#upload a').click(function(){
				$.cameraRoll.openDialog($('#uploadPopup'));
				$('#photos').css('visibility', 'hidden');
				return false;
			});
			
			// Add album link click to open dialog
			$('#createAlbum a').click(function () {
				$.cameraRoll.openDialog($('#addAlbumPopup'));
				$('#albums').css('visibility', 'hidden');
				return false;
			});

			// Remove click to open dialog
			$('#remove a').click(function(){
				$.cameraRoll.openDialog($('#removePopup'));
				$('#photos').css('visibility', 'hidden');
				return false;
			});
		},

		buildTable : function(data, userName) {
			var imageCounter = 0;
			var picTable = '<tr>';
			$.each(data.images, function(key, image){
				if(imageCounter < 4) {
					picTable += '<td><img src="' + image + '" rel="lightbox" /></td>';
					imageCounter++;
				}
				else { 
					imageCounter = 0;
					picTable += '</tr> <tr>';
				}
			});
			picTable += '</tr>'

			$('#pictureTable').append(picTable);

			$('img').click(function () {
				$.cameraRoll.viewImage(this);	
			});
		},

		uploadPhoto: function (options) {
			var settings = $.extend({
				form: null,
			}, options);
			settings.form.submit();
		},

//		uploadEnterKeyPress: function(event) {
//			if(event.keycode == 13 && ('#dropdownBox').dialog("isOpen") {
//				$('#photos').css('visibility', 'visible');
//				$('#upload-submit').click();
//			}
//		},

		viewImage: function (image) {
			var displayImage = $(image).clone();
			$('#imageWindow').html(displayImage);
			$(".ui-dialog-titlebar").hide();
			$.cameraRoll.openDialog($('#imagePopup'));
		},

		deletePhoto: function (options) {
			var settings = $.extend({
				image: null
			}, options);

			console.log(settings.image);

			if (confirm("Are you sure you want to delete this image")) {
				$.getJSON('./cameraRollPhp/deletePhoto.php?image=' + settings.image, function (data) {
					if (data.success) {
						window.location.reload();
					}
				});
			}
		},

		deleteAlbum: function (options) {
			var settings = $.extend({
				album: null,
				closeButton: null
			}, options);

			if (confirm("Are you sure you want to delete the album {0} and all of the images it contains?".format(settings.album))) {
				$.getJSON('./cameraRollPhp/deleteAlbum.php?album=' + settings.album, function (data) {
					console.log(data);
					if (data.success) {
						window.location.href = "./cameraRollHome.php";
					}
				});
			}
			else {
				$(settings.closeButton).click();
			}
		},

		manageProfile: function (options) {
			var settings = $.extend({
				firstName: null,
				lastName: null,
				update: false,
				close: function () { alert("no close function defined") }
			}, options);

			$.getJSON('./cameraRollPhp/manageProfile.php?firstName=' + settings.firstName.val() + '&lastName=' + settings.lastName.val() + '&update=' + settings.update, function (data) {
				if (data.getUserInfo) {
					settings.firstName.val(data.firstName);
					settings.lastName.val(data.lastName);
				}
				else if (data.update) {
					$('#mainPage h1').html('Welcome {0}'.format(data.firstName));
					settings.close();
				}
			});
		},

		updatePassword: function (options){
			var settings = $.extend({
				oldPassword: null,
				newPassword: null,
				confirmPassword: null,
				close: function () { alert("no close function defined") }
			}, options);

			if (settings.newPassword.val() == settings.confirmPassword.val() && settings.newPassword.val() != '') {
				$.getJSON('./cameraRollPhp/changePassword.php?oldPassword=' + settings.oldPassword.val() + '&newPassword=' + settings.newPassword.val(), function (data) {
					if (data.success) {
						settings.close();
					}
				});
			}
			else if (settings.newPassword.val() == '') {
				settings.newPassword.addClass('errorField');
			}
			else {
				settings.confirmPassword.addClass('errorField');
			}

			settings.newPassword.blur(function () {
				if ($(this).val() != '') {
					$(this).removeClass('errorField');
				}
			});

			settings.confirmPassword.blur(function () {
				if ($(this).val() == settings.newPassword.val() && settings.newPassword.val() != '') {
					$(this).removeClass('errorField');
				}
			});
		},

		updateEmail: function (options) {
			var settings = $.extend({
				oldEmail: null,
				newEmail: null,
				confirmEmail: null,
				close: function () { alert("no close function defined") }
			}, options);

			if (settings.newEmail.val() == settings.confirmEmail.val() && $.cameraRoll.validateEmail(settings.newEmail.val())) {
				if (confirm("Changing your email changes the email we use to send you your password and/or username.\n Continue?")) {
					$.getJSON('./cameraRollPhp/changeEmail.php?oldEmail=' + settings.oldEmail.val() + '&newEmail=' + settings.newEmail.val(), function (data) {
						if (data.success) {
							settings.close();
						}
					});
				}
				else {
					settings.close();
				}
			}
			else if (!$.cameraRoll.validateEmail(settings.newEmail.val())) {
				settings.newEmail.addClass('errorField');
			}
			else {
				settings.confirmEmail.addClass('errorField');
			}

			settings.newEmail.blur(function () {
				if($.cameraRoll.validateEmail($(this).val())){
					$(this).removeClass('errorField');
				}
			});
		}
	}
})(jQuery);
